package com.jason.redCherry.common;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 状态码管理器
 */
public class StatusCodeManager {
    private static Properties statusCodes = new Properties();// code码key,描述值
    private static Log logger = LogFactory.getLog(StatusCodeManager.class);

    static {
        init();
    }

    /**
     * 成功
     */
    public static final String SUCCESS = "0000";
    public static final String ERROR_PWD = "0001";
    public static final String ERROR_NO_USER = "0002";
    public static final String ERROR_TIMT_UNTIL = "0003";
    public static final String ERROR_APP_VERSION = "0004";
    public static final String ERROR_MAC = "0005";
    public static final String ERROR_UPDATE = "0006";
    public static final String ERROR_CANT_USE = "0007";


    public static String getCodeMsg(String statusCode) {

        return statusCodes.getProperty(statusCode);

    }

    private static void init() {

        InputStream in = null;

        try {

            in = findFileInput();

            SAXReader reader = new SAXReader();

            Document document = reader.read(in);

            Element element = document.getRootElement();

            List<Element> elements = element.elements("statuscode");

            for (Element oneElement : elements) {

                statusCodes.setProperty(oneElement.attributeValue("code"),
                        oneElement.attributeValue("msg"));

            }
            logger.info("StatusCodeManager.init" +
                    "StatusCodeManager" + "load properties success,size = "
                    + statusCodes.size());
        } catch (Exception e) {
            logger.error("StatusCodeManager.init" +
                    "StatusCodeManager" + "load properties failure");

        } finally {

            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }

        }

    }

    private static InputStream findFileInput() throws IOException {
        String path = StatusCodeManager.class.getPackage().getName()
                .replace('.', '/');
        final String fileName = "statuscode.xml";
        logger.info("path " + path);
        Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader()
                .getResources(path);
        InputStream in = null;
        while (dirs.hasMoreElements()) {
            URL url = dirs.nextElement();
            logger.info("protocol is " + url.getProtocol());
            if ("file".equals(url.getProtocol())) {
                String packagePath = URLDecoder.decode(url.getFile(), "UTF-8");
                File dir = new File(packagePath);
                // 如果不存在或者 也不是目录就直接返回
                if (!dir.exists() || !dir.isDirectory()) {
                    // log.warn("用户定义包名 " + packageName + " 下没有任何文件");
                    continue;
                }
                File[] files = dir.listFiles(new FileFilter() {

                    public boolean accept(File pathname) {

                        return pathname.isFile()
                                && pathname.getName().equals(fileName);
                    }
                });
                if (files != null && files.length > 0) {
                    in = new FileInputStream(files[0]);
                    break;
                }

            } else if ("jar".equals(url.getProtocol())) {
                // 获取jar
                JarFile jar = ((JarURLConnection) url.openConnection())
                        .getJarFile();
                // 从此jar包 得到一个枚举类
                JarEntry fileEntry = jar.getJarEntry(path + '/' + fileName);

                if (fileEntry != null) {

                    in = jar.getInputStream(fileEntry);
                    break;
                }
            }
        }

        return in;
    }

    public static void main(String[] args) {
        System.out.println(StatusCodeManager.getCodeMsg("0000"));
    }
}
